﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace MrPoetic.MatLab
{
    public sealed partial class DataMatrix
    {
        /// <summary>
        /// 质数筛法 - 算法发明人`丁者诚昊`
        /// (据说古希腊哲学家先想到这个算法~哈哈,但就算没有他我也能想到)
        /// </summary>
        /// <param name="Upper">上界</param>
        /// <returns>N上界以内的所有质数序列</returns>
        public static IEnumerable<Int64> PrimesIMPL(Int32 Upper)
        {
            // 0.造光源
            int radix = (int)Math.Sqrt(Upper);
            List<int> narrowMemory = new List<int> { 2, 3 };
            // 1.造基底平面
            for (int i = 3; i <= radix; i += 2)
            {
                if (Algebra.LambdaUtil.isPrime(i))
                    narrowMemory.Add(i);
            }
            // 2.造空间
            List<long> _primesList = new List<long>((int)Upper);
            for (int i = 0; i < Upper; i++)
            {
                _primesList.Add(i);
            }
            // 3.散射 [光量子散射算法] by.Dr.Dim 丁诚昊 1985~？
            for (int i = 0; i < narrowMemory.Count(); i++)
            {
                int times = 2;
                while (times * narrowMemory[i] < Upper)
                    _primesList[times++ * narrowMemory[i]] = 0;
            }
            List<long> MisteriousLinearTable = new List<long>();
            for (int i = 0; i < Upper; i++)
                if (_primesList[i] != 0)
                    MisteriousLinearTable.Add(_primesList[i]);

            // 将结果保存到本地静态变量中
            return MisteriousLinearTable;
        }

        /// <summary>
        /// 斐波那契数列
        /// </summary>
        /// <param name="Counts">斐波那契`数量` 注意:不是上界</param>
        /// <returns>长度为Counts的斐波那契序列结果集</returns>
        public static IEnumerable<Int64> FiboracciIMPL(Int32 Counts)
        {
            var _fiboList = new List<long> { 1, 1, 2 };
            int count = 0;
            while (count < Counts)
            {
                long x1 = _fiboList.Last();
                long x2 = _fiboList.ElementAt(_fiboList.Count() - 2);
                _fiboList.Add(x1 + x2);
                count++;
            }
            return _fiboList;
        }

        /// <summary>
        /// 2次幂数字组成的序列
        /// </summary>
        /// <param name="Upper">上界</param>
        /// <returns>返回上界N以内的所有2次幂数 注意不是数量Counts</returns>
        public static IEnumerable<Int64> _2TimesIMPL(Int32 Upper)
        {
            var rs = new Queue<long>(Upper);
            for (long i = 0; i < long.MaxValue; i++)
            {
                rs.Enqueue((long)Math.Pow(2, i));
                if (Upper-- == 0)
                    break;
            }
            return rs;
        }

        // 系统随机数
        static internal Random Seed { get { return new Random(); } }
    }
}
